package nuaa.service;

import nuaa.dao.IEvaluationDao;
import nuaa.domain.Evaluation;
import nuaa.domain.OrdinaryUser;
import nuaa.domain.User;
import nuaa.util.UtilSqlSession;
import nuaa.util.UtilString;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * 对数据库表evaluation的事务操作
 */
public class EvaluationService {

    /*dao层对象*/
    IEvaluationDao evaluationDao= UtilSqlSession.getSqlSession().getMapper(IEvaluationDao.class);

    public EvaluationService() throws IOException {
    }

    /**
     * 查找所有用户对当前用户的评价对象
     * @param theOtherId
     * @return 所有评价对象
     */
    public List<Evaluation> findAllTheOtherToUser(Integer theOtherId) throws IOException {
        //获取对象
        List<Evaluation> otherEvaluations = evaluationDao.findAllTheOtherToUser(theOtherId);
        UserService userService = new UserService();
        //改变遍历方式，使用迭代器遍历
        Iterator<Evaluation> iter = otherEvaluations.iterator();
        while (iter.hasNext()){
            //iter.next()就是当前的对象
            Evaluation evaluation = iter.next();
            String userName = userService.findUserNameByUserId(evaluation.getUserId());
            //判别是否为空
            if (UtilString.isEmpty(userName)){
                //移除这个
                iter.remove();
            }else { //否则设置
                evaluation.setUserName(userName);
            }
        }
        return otherEvaluations;
    }

    /**
     * 根据当前用户Id查找其他的被评价用户
     * @param userId
     */
    public List<Evaluation> findAllUserToTheOther(Integer userId) throws IOException {
        //获取数据
        List<Evaluation> myEvaluations = evaluationDao.findAllUserToTheOther(userId);
        UserService userService = new UserService();
        //获取迭代器对象
        Iterator<Evaluation> iter = myEvaluations.iterator();
        while (iter.hasNext()){
            Evaluation evaluation = iter.next();
            String userName = userService.findUserNameByUserId(evaluation.getTheOtherId());
            //判别是否为空
            if (UtilString.isEmpty(userName)){
                //移除这个
                iter.remove();
            }else { //否则设置
                evaluation.setUserName(userName);
            }
        }
        //返回
        return myEvaluations;
    }

    /**
     * 根据用户userId获取分数
     * @param userId
     * @return
     */
    public Double findScoreByUserId(Integer userId) {
        //调用dao层方法获取分数
        Double score=evaluationDao.findScoreByUserId(userId);
        //返回分数
        return score;
    }
}
